<template>
  <MySplitPanes>
    <pane size="15" min-size="15" max-size="15">
      <div class="my-flex-column w100 h100">
        <ProductSeriesNodeMenu @node-click="onProductSeriesNodeClick" select-first-node></ProductSeriesNodeMenu>
      </div>
    </pane>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" @submit.stop.prevent>
            <el-form-item label="产品详情">
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">
            <div>
              <el-button v-auth="'api:industry:product-model:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增
              </el-button>
            </div>
            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>
          <el-table ref="tableRef" v-loading="state.loading" :data="state.productModelListData"
            @sort-change="onSortChange" row-key="id" border>
            <el-table-column type="selection" />
            <el-table-column prop="productCode" label="产品代号" width="100" show-overflow-tooltip />
            <el-table-column prop="productName" label="产品名称" width="100" show-overflow-tooltip />
            <el-table-column prop="routeOrder" label="工艺路线序号" width="120" show-overflow-tooltip align="center" />
            <el-table-column prop="formulaOrder" label="设备配方序号" width="120" show-overflow-tooltip align="center" />
            <el-table-column prop="sort" label="排序" width="80" align="center" sortable="custom" show-overflow-tooltip />
            <el-table-column label="状态" width="80" align="center" fixed="right">
              <template #default="{ row }">
                <el-switch v-if="auth('api:industry:product-model:set-enable')" v-model="row.enabled"
                  :loading="row.loading" :active-value='true' :inactive-value='false' inline-prompt active-text="开启"
                  inactive-text="关闭" :before-change="() => onSetEnable(row)" />
                <template v-else>
                  <el-tag type="success" v-if="row.enabled">启用</el-tag>
                  <el-tag type="danger" v-else>禁用</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" header-align="center" align="center" fixed="right">
              <template #default="{ row }">
                <el-button v-auth="'api:industry:product-model:update'" icon="ele-EditPen" size="small" text
                  type="primary" @click="onEdit(row)">编辑</el-button>
                <my-dropdown-more
                  v-auths="['api:industry:product-model:soft-delete', 'api:industry:product-model:issue-formula-order', 'api:industry:product-model:set-last-product-route']">
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-if="auth('api:industry:product-model:issue-formula-order')"
                        @click="onSetIssueFormulaOrder(row)">下发当前配方</el-dropdown-item>
                      <el-dropdown-item v-if="auth('api:industry:product-model:set-last-product-route')"
                        @click="onSetLastProductRoute(row)">更新当前工艺路线</el-dropdown-item>
                      <el-dropdown-item v-if="auth('api:industry:product-model:soft-delete')"
                        @click="onDelete(row)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </my-dropdown-more>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 10px">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
        <ProductModelForm ref="productSericesFormRef" :title="state.productModelFormTitle"></ProductModelForm>
        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure"></MyFilterDialog>
      </div>
    </pane>
  </MySplitPanes>

</template>
<script setup lang="ts" name="industry/product-Model">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { PageInputProductModelGetPageInput, ProductModelGetPageInput, ProductModelGetPageOutput, ProductModelGetOutput, SortInput, ProductSeriesGetOutput } from '/@/api/industry/data-contracts'
import { ProductModelApi } from '/@/api/industry/ProductModel'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable } from 'element-plus'
import { Pane } from 'splitpanes'

const ProductSeriesNodeMenu = defineAsyncComponent(() => import('/@/views/industry/product-series/compoents/product-series-node-menu.vue'))
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MyDropdownMore = defineAsyncComponent(() => import('/@/components/my-dropdown-more/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const ProductModelForm = defineAsyncComponent(() => import('./compoents/product-model-form.vue'))
const productSericesFormRef = ref()
const { proxy } = getCurrentInstance() as any
const getSortList = (data: { prop: string; order: any }) => {
  return [
    {
      propName: data.prop,
      order: data.order === 'ascending' ? 0 : data.order === 'descending' ? 1 : undefined,
    },
  ] as [SortInput]
}

const defalutSort = { prop: 'sort', order: 'ascending' }
const state = reactive({
  loading: false,
  showQuery: true,
  productModelFormTitle: '',
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
    sortList: getSortList(defalutSort),
    filter: {
      productSeriesId: 0,
      seriesName: ''
    } as ProductModelGetPageInput,
    dynamicFilter: {
    },
  } as PageInputProductModelGetPageInput,
  productModelListData: [] as Array<ProductModelGetPageOutput>,
  filters: [
    {
      field: 'productCode',
      operator: 'Contains',
      description: '产品代号',
      componentName: 'el-input',
      defaultSelect: true,
    },
    {
      field: 'productName',
      operator: 'Contains',
      description: '产品名称',
      componentName: 'el-input',
      defaultSelect: false,
    },
  ] as Array<DynamicFilterInfo>,
})

onMounted(() => {
  onQuery()
  eventBus.off('refreshProductModel')
  eventBus.on('refreshProductModel', async () => {
    onQuery()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshProductModel')
})

const onSortChange = (data: { column: any; prop: string; order: any }) => {
  state.pageInput.sortList = getSortList(data)
  onQuery()
}
//查询分页
const onQuery = async () => {
  state.loading = true
  const res = await new ProductModelApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.productModelListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}
const onFilterSure = (dynamicFilter: any) => {
  state.pageInput.dynamicFilter = dynamicFilter
  onQuery()
}
//新增
const onAdd = (row: ProductModelGetOutput) => {
  state.productModelFormTitle = `新增系列【${state.pageInput.filter?.seriesName}】产品详情`
  productSericesFormRef.value.open({ productSeriesId: state.pageInput.filter?.productSeriesId })
}

//修改
const onEdit = (row: ProductModelGetOutput) => {
  state.productModelFormTitle = `编辑产品【${row.productCode}】信息`
  productSericesFormRef.value.open(row)
}

//删除
const onDelete = (row: ProductModelGetOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除产品代号为【${row.productCode}】?`)
    .then(async () => {
      await new ProductModelApi().softDelete({ id: row.id }, { loading: true, showSuccessMessage: true })
      onQuery()
    })
    .catch(() => { })
}

//启用或禁用
const onSetEnable = (row: ProductModelGetOutput & { loading: boolean }) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要${row.enabled ? '禁用' : '启用'}产品代号为：【${row.productCode}】?`)
      .then(async () => {
        row.loading = true
        const res = await new ProductModelApi()
          .setEnable({ productModelId: row.id, enabled: !row.enabled }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
            row.loading = false
          })
        if (res && res.success) {
          resolve(true)
        } else {
          reject(new Error('Cancel'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

//切换配方
const onSetIssueFormulaOrder = (row: ProductModelGetOutput) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要下发当前配方序号【${row.formulaOrder}】? `)
      .then(async () => {
        const res = await new ProductModelApi()
          .issueFormulaOrder({ deviceFormulaId: row.formulaId }, { showSuccessMessage: true })
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
          })
        if (res && res?.success) {
          resolve(true)
        } else {
          reject(new Error('Error'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

//更新工艺路线
const onSetLastProductRoute = (row: ProductModelGetOutput) => {
  return new Promise((resolve, reject) => {
    proxy.$modal
      .confirm(`确定要更新当前工艺路线【${row.routeOrder}】? `)
      .then(async () => {
        const res = await new ProductModelApi()
          .setLastProductRoute()
          .catch(() => {
            reject(new Error('Error'))
          })
          .finally(() => {
          })
        if (res&&res?.success) {
          resolve(true)
        } else {
          reject(new Error('Error'))
        }
      })
      .catch(() => {
        reject(new Error('Cancel'))
      })
  })
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}

const onProductSeriesNodeClick = (node: ProductSeriesGetOutput | null) => {
  if (state.pageInput.filter) {
    state.pageInput.filter.productSeriesId = node?.id
    state.pageInput.filter.seriesName = node?.seriesName
  }
  onQuery()
}
</script>